package com.k8sops.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.k8sops.backend.entity.DOSProjectVersion;
import com.k8sops.backend.mapper.DOSProjectVersionMapper;
import com.k8sops.backend.service.DOSProjectVersionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 项目版本服务实现类
 */
@Service
public class DOSProjectVersionServiceImpl extends ServiceImpl<DOSProjectVersionMapper, DOSProjectVersion> implements DOSProjectVersionService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addProjectVersion(DOSProjectVersion projectVersion) {
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        projectVersion.setCreatedAt(now);
        projectVersion.setUpdatedAt(now);
        
        // 保存项目版本
        boolean result = save(projectVersion);
        
        // 如果保存成功，更新项目的最新版本号
        if (result) {
            baseMapper.updateProjectLatestVersion(projectVersion.getProjectId(), projectVersion.getVersionNumber());
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateProjectVersion(DOSProjectVersion projectVersion) {
        // 设置更新时间
        projectVersion.setUpdatedAt(LocalDateTime.now());
        
        return updateById(projectVersion);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteProjectVersionById(Long id) {
        return removeById(id);
    }

    @Override
    public DOSProjectVersion getProjectVersionById(Long id) {
        return getById(id);
    }

    @Override
    public IPage<DOSProjectVersion> pageProjectVersions(Integer page, Integer size, Integer projectId) {
        // 使用自定义查询方法，避免列名映射问题
        if (projectId != null) {
            return baseMapper.pageVersionsByProjectId(new Page<>(page, size), projectId);
        } else {
            // 如果没有指定项目ID，返回空结果
            return new Page<>(page, size);
        }
    }

    @Override
    public DOSProjectVersion getLatestProjectVersion(Integer projectId) {
        // 使用自定义查询方法，避免列名映射问题
        return baseMapper.getLatestVersionByProjectId(projectId);
    }
}
